#!/usr/bin/evn python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch


from models import *
from ptzmodels import *
from common.constants import *

import string

webapp.template.register_template_library('common.customtags')

"""
Allows users to build a mesh or set of correspondences.
"""
class Build(webapp.RequestHandler):
    def get(self):
        import urllib2
        from google.appengine.api import urlfetch
        from google.appengine.api import users
        
        sceneId = self.request.get('scene')
        scene = Scene.get_by_key_name('scene' + str(sceneId))
        
        amosId = None
        url = None
        
        amosId = self.request.get('amosId')
        url = self.request.get('url')

        user = users.get_current_user()
        if not user:
            username = ''
        else:
            username = user.nickname()
        
        logInURL = users.create_login_url(self.request.url)
        logOutURL = users.create_logout_url(self.request.url)
        
        createScn = self.request.get('createScn')
        if createScn == "True":
            createScn = True
        else:
            createScn = False
        
        if amosId:
            # if there's an AMOS id, get the URL from there.
            try:
                result = urllib2.urlopen(AMOS_ID_TO_URL + str(amosId))
                result = result.read()
                if (result != '' and result[0:7] == 'http://'):
                    url = result
                else:
                    raise urlfetch.DownloadError
            except (urlfetch.DownloadError, urllib2.HTTPError):
                values = {
                    'message' : 'Couldn\'t load AMOS ID ' + amosId + '.',
                    'username' : username,
                    'logInURL' :logInURL,
                    'logOutURL' :logOutURL
                }
                self.response.out.write(template.render(TEMPLATE_DIRECTORY + 'middle.html', values))
                return
            
        elif url:
            # if no amos id, get image URL from given URL.
            try:
                # see if there is an AMOS ID to go with this URL.
                result = urllib2.urlopen(AMOS_URL_TO_ID + str(url))
                result = result.read()
                if (result != '-1'):
                    amosId = str(result)
            except urlfetch.DownloadError:
                # if this fails, then don't worry.  Just keep chugging along.
                amosId = None

        # otherwise, get it from the scene ID.
        elif sceneId:
            scene = Scene.get_by_key_name('scene' + sceneId)
            if not scene:
                values = {
                    'message' : 'Scene ' + sceneId + ' does not exist.',
                    'username' : username,
                    'logInURL' :logInURL,
                    'logOutURL' :logOutURL
                }
                self.response.out.write(template.render(TEMPLATE_DIRECTORY + 'middle.html', values))
                return
            url = scene.url
        
        
        if not url:
            return self.redirect('/')
        
        # test if this is a real image URL.
        try:
            url = url.replace('%3A', ':')
            response = urllib2.urlopen(url)
            data = response.read()
        except (ValueError,  urllib2.URLError, IOError, urlfetch.DownloadError):
            values = {
                    'message' : 'URL (' + url + ') could not be loaded.',
                    'username' : username,
                    'logInURL' :logInURL,
                    'logOutURL' :logOutURL
            }
            self.response.out.write(template.render(TEMPLATE_DIRECTORY + 'middle.html', values))
            return

        # grab the scene from the url, if it exists.
        # note that we might already have the scene at this point.
        if not scene and not createScn:
            scene1 = Scene.all().filter('is_private =', False).filter('url =', url) #all the public scenes
            scene2 = Scene.all().filter('is_private =', True).filter('owner =',user).filter('url =', url) #all private scenes I'm owner of
            #scene = scene1.fetch(10000)+scene2.fetch(10000) #all scenes we care about
            gc1 = scene1.count()
            gc2 = scene2.count()
            gc = gc1 + gc2
            if gc > 1:
                values = {
                    'message' : 'There was more than one scene with the URL "'+url+'". <br/>Please pick the scene you want to edit from the scenes in <a href="/scenesURL?url='+url+'">this link</a>.',
                    'username' : username,
                    'logInURL' :logInURL,
                    'logOutURL' :logOutURL
                }
                self.response.out.write(template.render(TEMPLATE_DIRECTORY + 'middle.html', values))
                return
            elif gc1 == 1:
                scene = scene1.get()
            elif gc2 == 1:
                scene = scene2.get()
            
        if scene and not createScn:
            meshes = Mesh.all().filter('scene =', scene).fetch(limit=100)
            correspondences = Correspondence.all().filter('scene =', scene).fetch(limit=100)
            calibration = Calibration.get_by_key_name('calib' + str(scene.index))
        else:
            scene = None
            meshes = None
            correspondences = None
            calibration = None
    
        allCorrs = Correspondence.all().filter('scene = ', scene)
        numPts = allCorrs.count()

        # BuildAt means the url specifies where to start the build window camera
        buildAt = self.request.get('buildAt')  or 0
        lat = self.request.get('lat') or 0
        lon = self.request.get('lon') or 0
        alt = self.request.get('alt') or 0
        roll = self.request.get('roll') or 0
        tilt = self.request.get('tilt') or 0
        head = self.request.get('head') or 0
        
        values = {
            'url' : url,
            'scene' : scene,
            'createScn': createScn,
            'correspondences' : correspondences,
            'meshes' : meshes,
            'amosId' : amosId,
            'calibration' : calibration,
            'username': username,
            'logInURL': logInURL,
            'logOutURL': logOutURL,
            'numPts': numPts,
            'requiredNumCorrs' : CORRESPONDENCES_REQUIRED_FOR_CALIBRATION,

            'buildAt' : buildAt,
            'lat'  : lat,
            'lon'  : lon,
            'alt'  : alt,
            'roll' : roll,
            'tilt' : tilt,
            'head' : head
        }
        self.response.out.write(template.render(TEMPLATE_DIRECTORY + 'build.html', values))
        
    